package main

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/lib/pq"
)

const (
	host     = "localhost"
	port     = 5432
	user     = "admin"
	password = "admin"
	dbname   = "testdb"
)

type Teacher struct {
	id   int
	name string
	age  int
}

func main() {
	psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable",
		host, port, user, password, dbname)
	db, err := sql.Open("postgres", psqlInfo)
	if err != nil {
		panic(err)
	}
	defer db.Close()

	err = db.Ping() //测试服务器是否在线
	if err != nil {
		panic(err)
	}

	fmt.Println("Successfully connected!")

	tx, err := db.Begin()
	if err != nil {
		log.Fatal(err)
	}
	defer tx.Rollback()
	stmt, err := tx.Prepare(`INSERT INTO t123(name,age) VALUES($1, $2) RETURNING id`)
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close() // danger!
	var lastid int
	for i := 0; i < 10; i++ {
		err = stmt.QueryRow("agef", i).Scan(&lastid)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(lastid)
		if i == 5 {
			tx.Commit()
		} else if i > 5 {
			tx.Rollback()
		}
	}

	err = tx.Commit()
	if err != nil {
		log.Fatal(err)
	}
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}
